package com.may.shiro.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.may.entity.Permission;
import com.may.entity.Role;
import com.may.entity.User;
import com.may.service.UserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author mayuanbao
 * @date 2020-07-09 20:18
 */
public class CustomerRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;

    /**
     * 授权
     * @author mayuanbao
     * @date 2020/11/05 10:30
     * @param principals principals
     * @return org.apache.shiro.authz.AuthorizationInfo
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 获取身份信息
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();
        // 根据主身份信息获取角色和权限信息
        User user = userService.findRoleByUserName(primaryPrincipal);
        List<Role> roles = user.getRoles();
        if (CollectionUtils.isNotEmpty(roles)) {
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            roles.forEach(role -> {
                simpleAuthorizationInfo.addRole(role.getName());
                // 权限信息
                List<Permission> permissions = userService.findPermissionByRoleId(role.getId());
                if (CollectionUtils.isNotEmpty(permissions)) {
                    permissions.forEach(permission -> simpleAuthorizationInfo.addStringPermission(permission.getName()));
                }
            });
            return simpleAuthorizationInfo;
        }
        return null;
    }

    /**
     * 认证
     * @author mayuanbao
     * @date 2020/11/05 10:29
     * @param token token
     * @return org.apache.shiro.authc.AuthenticationInfo
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("name", username);
        User user = userService.getOne(wrapper);
        if (!ObjectUtils.isEmpty(user)) {
            return new SimpleAuthenticationInfo(user.getName(), user.getPassword(),
                    ByteSource.Util.bytes(user.getSalt()), getName());
        }
        return null;
    }
}
